package com.wn.Exception;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.springframework.validation.BindException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalException {
    //后端获取前端的文件时数据监测的异常
    @ExceptionHandler(BindException.class)
    public Map<String,Object> BindException(BindingResult bindingResult){
        Map<String,Object> map = new HashMap<>();
        //获取所有的后台验证的错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for(FieldError error : fieldErrors){
            //获取异常的属性的名称
            String fieldName = error.getField();
            //获取属性的message
            String message = error.getDefaultMessage();
            map.put(fieldName,message);
        }
        return map;
    }
}
